package com.controller;

import com.dto.HttpClientMapResult;
import com.service.iml.UserService;
import com.utils.JwtTokenUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Map;

/**
 * @Description 上传需要使用 @RestController 注解
 */
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Resource
    private UserService userService;
    @Resource
    private JwtTokenUtil jwtTokenUtil;

    /**
     * @Description 上传头像，客户端的请求文件 key 要设置为默认的 file ( key : 'file' ) ( name : 'file' )
     * @param file
     * @return
     */
    @PostMapping("/user/avatar")
    public Map uploadUserAvatar(HttpServletRequest request, MultipartFile file) {
        boolean res = false;
        try {
            System.out.println("ContentType: " + file.getContentType());
            System.out.println("Name: " + file.getName());
            System.out.println("Size: " + file.getSize());

            byte[] avatar = file.getBytes();
            String openid = jwtTokenUtil.getIdFromToken(request);
            Integer id = userService.getUserId(openid);
            res = userService.changeUserAvatar(id, avatar);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new HttpClientMapResult()
                .setStatusCode(res ? HttpURLConnection.HTTP_OK : HttpURLConnection.HTTP_INTERNAL_ERROR)
                .putMsg(res ? "上传成功" : "上传失败");
    }

}
